import { createUniqueId } from './utils.js';

export const callbacks = {};

chrome.runtime.onMessage.addListener((data) => {
  const { callbackId } = data;
  const callback = callbacks[callbackId];
  if (callback) {
    callback.resolve(data);
    delete callbacks[callbackId];
  }
})

const pushCallback = (param) => {
  const uniqueId = `extension_callback_${createUniqueId()}`;
  callbacks[uniqueId] = {
    resolve: param.resolve,
    reject: param.reject,
  };
  return uniqueId;
};

export const callNative = ({ method, data }) => {
  return new Promise((resolve, reject) => {
    const id = pushCallback({ resolve, reject });
    chrome.runtime.sendMessage({
      method,
      data,
      callbackId: id,
    });
  }).then(({ data, success }) => {
    if (success) {
      return data
    }
    throw data
  });
};

export const fetchAll = (urls, cacheKey, type = 'text') => {
  return callNative({
    method: 'fetchAll',
    data: {
      urls,
      cacheKey,
      type,
    },
  });
}

export const setStorage = (key, value) => {
  return callNative({
    method: 'setStorage',
    data: {
      key,
      value,
    },
  });
};

export const getStorage = (key) => {
  return callNative({
    method: 'getStorage',
    data: {
      key,
    },
  });
};

export const setCache = (key, value) => {
  return callNative({
    method: 'setCache',
    data: {
      key,
      value,
    },
  });
};

export const getCache = (key) => {
  return callNative({
    method: 'getCache',
    data: {
      key,
    },
  });
};